package com.lilosoft.core.base;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.plugins.Page;
import com.lilosoft.core.utils.commons.StringUtils;
import com.lilosoft.core.utils.commons.UUIDUtils;

/**
 * Service基类
 *
 * @author qiusheng
 * @Date 2018-10-30
 */
@SuppressWarnings("rawtypes")
public abstract class CrudService<D extends CrudDao<T>, T extends BaseBean> extends BaseService {

	/**
	 * 持久层对象
	 */
	@Autowired
	protected D dao;

	/**
	 * 获取单条数据
	 * @param id
	 * @return HashMap<String, Object>
	 */
	public HashMap<String, Object> getById(String id) {
		return dao.getById(id);
	}

	/**
	 * 获取单条数据
	 * @param paramsMap
	 * @return HashMap<String, Object>
	 */
	public HashMap<String, Object> getByParams(HashMap<String, Object> paramsMap) {
		return dao.getByParams(paramsMap);
	}

	/**
	 * 查询列表数据
	 * @param entity
	 * @return
	 */
	public List<HashMap<String, Object>> findList(HashMap<String, Object> paramsMap) {
		return dao.findList(new RowBounds(), paramsMap);
	}

	/**
	 * 查询分页数据
	 * @param page 分页对象
	 * @param entity
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Page findPage(Page page, HashMap<String, Object> paramsMap) {
		page.setRecords(dao.findList(page, paramsMap));
		page.setTotal(page.getTotal());
		return page;
	}

	/**
	 * 保存数据（插入或更新）
	 * @param entity
	 */
	@Transactional(readOnly = false)
	public void save(T entity) {
		if (StringUtils.isEmpty(entity.getId())){
			entity.setId(UUIDUtils.createUUId());
			dao.insert(entity);
		}else{
			if(dao.getById(entity.getId()) == null){
				dao.insert(entity);
			}else {
				dao.update(entity);
			}
		}
	}

	/**
	 * 删除数据
	 * @param entity
	 */
	@Transactional(readOnly = false)
	public Boolean delete(String id) {
		return dao.delete(id)>0;
	}

	/**
	 * 从Map里获取指定Key的Value
	 * @param jsonMap
	 * @param key
	 * @return
	 */
	public String getMapValue(Map<String, Object> jsonMap, String key) {
		String result = "";
		if(jsonMap != null){
			Object obj = jsonMap.get(key);
			if(obj != null){
				result = obj.toString();
			}
		}
		return result;
	}

	/**
	 * 从List集合中找到对应Key的Map对象
	 * @param nextUserList
	 * @param taskDefinitionKey
	 * @return
	 */
	public Map<String,Object> findInMapList(List<Map<String,Object>> mapList, String key, String value) {
		if(mapList!=null && mapList.size()>0) {
			for (Map<String, Object> map : mapList) {
				if(value.equals(map.get(key))) {
					return map;
				}
			}
		}
		return null;
	}
}
